import movieTpl from '../views/movie.html'
import movieListTpl from '../views/movie_list.html'

import Http from '../model/http'
import BScroll from 'better-scroll'

class MovieController {
    constructor() {
        this.count = 12
        this.timer = null
    }
    async render() {
        $('header').html('猫眼电影')
        $("main").html(movieTpl)
        let movieCache = await Http.movieOnInfoList()
        this.movieIds = movieCache.movieIds
        let movieList = movieCache.movieList
        $.each(movieList, function(index, item) {
            item.img = item.img.split('w.h/')[1]
        })
        let movieListHtml = template.render(movieListTpl, { movieList })
        $(".movie-list ul").html(movieListHtml)

        this.bScroll = new BScroll('.movie-list', {
            probeType: 1,
            pullUpLoad: {
                threshold: -20
            }
        })
        this.bScroll.on('pullingUp', this.debounce(this.renderMore, 800))
    }

    debounce(callback, delay) {
        this.timer = null; // 闭包延长timer生命周期
        return () => {
            clearTimeout(this.timer); // 重复调用清空上一次计时器，重新计时
            this.timer = setTimeout(() => {
                callback.call(this) // 主体回调函数
            }, delay)
        }
    }

    async renderMore() {
        let data = ''
        for (let i = 0; i < 10; i++) {
            data += i < 9 ? this.movieIds[this.count++] + ',' : this.movieIds[this.count++]
        }
        let movieCache = await Http.moreMoveList(data)
        let movieList = movieCache.coming
        $.each(movieList, function(index, item) {
            item.img = item.img.split('w.h/')[1]
        })
        let movieListHtml = template.render(movieListTpl, { movieList })
        $(".movie-list ul").html($(".movie-list ul").html() + movieListHtml)
        this.bScroll.refresh()
        this.bScroll.finishPullUp()
    }
}

export default new MovieController()